<template>
  <div class="cu-common-layout">
    <div class="cu-common-layout-center">
      <!-- 主要查询条件 -->
      <el-row class="cu-common-search-box" :gutter="16">
        <el-form @submit.native.prevent :model="query">
          <el-col :span="6">
            <el-form-item label="师训项目">
              <el-select ref="trainSelect" v-model="query.trainId" placeholder="请选择师训项目" filterable clearable style="width: 100%">
                <el-option v-for="item in trainOptions" :key="item.id" :label="item.title" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="老师姓名">
              <el-input v-model="query.teacherName" placeholder="请输入老师姓名" clearable style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="签到日期">
              <el-date-picker v-model="query.signDate" type="daterange" value-format="yyyy-MM-dd" format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="签到时段">
              <el-select v-model="query.period" placeholder="请选择签到时段" clearable style="width: 100%">
                <el-option label="上午" value="AM"></el-option>
                <el-option label="下午" value="PM"></el-option>
                <el-option label="晚上" value="EVE"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="签到状态">
              <el-select v-model="query.status" placeholder="请选择签到状态" clearable style="width: 100%">
                <el-option label="正常签到" value="Normal"></el-option>
                <el-option label="迟到" value="Late"></el-option>
                <el-option label="请假" value="Leave"></el-option>
                <el-option label="早退" value="EarlyLeave"></el-option>
                <el-option label="缺勤" value="Absent"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="签到方式">
              <el-select v-model="query.method" placeholder="请选择签到方式" clearable style="width: 100%">
                <el-option label="二维码签到" value="QR"></el-option>
                <el-option label="手动签到" value="MANUAL"></el-option>
                <el-option label="自动生成" value="AUTO"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="校区筛选">
              <el-select v-model="query.campusId" placeholder="请选择校区" clearable style="width: 100%">
                <el-option v-for="campus in campusOptions" :key="campus.id" :label="campus.name" :value="campus.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()" native-type="submit">{{ $t('common.search') }}</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()" style="margin-left: 8px">{{ $t('common.reset') }}</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="cu-common-layout-main cu-flex-main">
        <div class="cu-common-head">
          <div>
            <el-button type="primary" icon="el-icon-plus" @click="handleManualSign" v-has="'btn_manual_sign'">手动签到</el-button>
            <el-button type="success" icon="el-icon-plus" @click="handleBatchManualSign" v-has="'btn_batch_sign'">批量手动签到</el-button>
            <el-button type="warning" icon="el-icon-edit" @click="handleBatchEdit" :disabled="!multipleSelection.length" v-has="'btn_batch_edit'">批量编辑</el-button>

            <el-button type="success" icon="el-icon-view" @click="handleSignOverview" v-has="'btn_sign_overview'">签到概览</el-button>
            <el-button type="primary" icon="el-icon-download" @click="handleExport" v-has="'btn_export'">导出记录</el-button>
            <el-button type="warning" icon="el-icon-document" @click="handleAuditLog" v-has="'btn_audit_log'">审计日志</el-button>
          </div>
          <div class="cu-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <!-- 未选择师训项目时的提示 -->
        <div v-if="!query.trainId && !listLoading" class="empty-state">
          <el-empty description="请先选择师训项目，然后点击搜索按钮查询签到记录">
            <el-button type="primary" @click="$refs.trainSelect && $refs.trainSelect.focus()">选择师训项目</el-button>
          </el-empty>
        </div>

        <custom-table v-else v-loading="listLoading" :data="list">
          <el-table-column type="selection" width="55" align="center" @selection-change="handleSelectionChange"></el-table-column>
          <el-table-column prop="teacherName" label="老师姓名" width="120" align="center"></el-table-column>
          <el-table-column prop="signDate" label="签到日期" width="120" align="center" sortable="custom" :formatter="custom.tableDateFormat"></el-table-column>
          <el-table-column prop="period" label="签到时段" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="getPeriodTagType(scope.row.period)" size="small">
                {{ getPeriodLabel(scope.row.period) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="签到状态" width="120" align="center">
            <template slot-scope="scope">
              <el-tag :type="getStatusTagType(scope.row.status)" size="small" class="status-tag-enhanced">
                <i :class="getStatusIcon(scope.row.status)" class="status-icon"></i>
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="method" label="签到方式" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="getMethodTagType(scope.row.method)" size="small">
                {{ getMethodLabel(scope.row.method) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="signTime" label="签到时间" :formatter="custom.tableDateTimeFormat" align="center" width="160px"></el-table-column>
          <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" fixed="right" width="250px" align="center">
            <template slot-scope="scope">
              <table-opts @edit="handleEditRecord(scope.row)" @del="handleDelete(scope.row)">
                <el-button type="text" v-has="'btn_detail'" @click="handleDetail(scope.row)">详情</el-button>
                <el-button type="text" v-has="'btn_edit_status'" @click="handleEditStatus(scope.row)">修改状态</el-button>
              </table-opts>
            </template>
          </el-table-column>
        </custom-table>

        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
    </div>

    <ManualSignForm v-if="manualSignFormVisible" ref="manualSignForm" @refresh="search" />
    <BatchManualSignForm v-if="batchManualSignFormVisible" ref="batchManualSignForm" @refresh="search" />

    <EditStatusForm v-if="editStatusFormVisible" ref="editStatusForm" @refresh="search" />
    <EditRecordForm v-if="editRecordFormVisible" ref="editRecordForm" @refresh="search" />
    <BatchEditForm v-if="batchEditFormVisible" ref="batchEditForm" @refresh="search" />

    <DetailDialog v-if="detailDialogVisible" ref="detailDialog" />

    <SignOverviewDialog v-if="signOverviewDialogVisible" ref="signOverviewDialog" />
    <AuditLogDialog v-if="auditLogDialogVisible" ref="auditLogDialog" />
  </div>
</template>

<script>
import { getTrainSignRecordList, exportSignRecords } from '@/api/campus/trainSignRecord'
import { getTrainSelector } from '@/api/campus/train'
import ManualSignForm from './ManualSignForm'
import BatchManualSignForm from './BatchManualSignForm'

import EditStatusForm from './EditStatusForm'
import EditRecordForm from './EditRecordForm'
import BatchEditForm from './BatchEditForm'

import DetailDialog from './DetailDialog'

import SignOverviewDialog from './SignOverviewDialog'
import AuditLogDialog from './AuditLogDialog'

export default {
  name: 'train_sign_record',
  components: {
    ManualSignForm,
    BatchManualSignForm,
    EditRecordForm,
    BatchEditForm,

    EditStatusForm,

    DetailDialog,

    SignOverviewDialog,
    AuditLogDialog
  },
  data() {
    return {
      query: {
        trainId: undefined,
        teacherName: undefined,
        signDate: undefined,
        period: undefined,
        status: undefined,
        method: undefined,
        campusId: undefined
      },
      campusOptions: [],
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'signTime desc'
      },
      trainOptions: [],
      manualSignFormVisible: false,
      batchManualSignFormVisible: false,

      editStatusFormVisible: false,
      editRecordFormVisible: false,
      batchEditFormVisible: false,

      detailDialogVisible: false,

      signOverviewDialogVisible: false,
      auditLogDialogVisible: false
    }
  },
  async created() {
    // 默认不加载数据，需要选择师训项目后才能查询
    this.listLoading = false
    await this.getTrainOptions()
  },
  methods: {
    async getTrainOptions() {
      try {
        const res = await getTrainSelector()
        if (res.code === 200) {
          this.trainOptions = res.data || []
        }
      } catch (error) {
        console.error('获取师训列表失败:', error)
      }
    },
    initData() {
      // 检查是否选择了师训项目
      if (!this.query.trainId) {
        this.$message.warning('请先选择师训项目')
        this.list = []
        this.total = 0
        this.listLoading = false
        return
      }

      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      getTrainSignRecordList(query).then(res => {
        this.list = res.data.list || res.rows || []
        this.total = res.data.pagination ? res.data.pagination.total : res.total || 0
        this.listLoading = false
      })
    },
    search() {
      // 检查是否选择了师训项目
      if (!this.query.trainId) {
        this.$message.warning('请先选择师训项目')
        return
      }

      this.manualSignFormVisible = false
      this.batchManualSignFormVisible = false

      this.editStatusFormVisible = false

      this.detailDialogVisible = false

      this.auditLogDialogVisible = false
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'signTime desc'
      }
      this.initData()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'signTime desc'
      }
      // 重置后清空数据，不自动加载
      this.list = []
      this.total = 0
      this.listLoading = false
    },
    // 快速筛选方法
    quickFilter(status) {
      this.query.status = status
      this.listQuery.currentPage = 1
      this.search()
    },
    // 导出筛选结果
    async handleExportFiltered() {
      try {
        this.$message.success('导出功能开发中...')
      } catch (error) {
        this.$message.error('导出失败：' + error.message)
      }
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    handleSortChange(column) {
      this.listQuery.orderBy = column.prop
      this.listQuery.isAsc = column.order === 'ascending'
      this.initData()
    },
    handleManualSign() {
      if (!this.query.trainId) {
        this.$message.warning('请先选择师训')
        return
      }
      this.manualSignFormVisible = true
      this.$nextTick(() => {
        this.$refs.manualSignForm.init(this.query.trainId)
      })
    },
    handleBatchManualSign() {
      if (!this.query.trainId) {
        this.$message.warning('请先选择师训')
        return
      }
      this.batchManualSignFormVisible = true
      this.$nextTick(() => {
        // 批量手动签到针对没有签到的老师，不依赖已选择的记录
        this.$refs.batchManualSignForm.init(this.query.trainId, [])
      })
    },



    
    handleSignOverview() {
      if (!this.query.trainId) {
        this.$message.warning('请先选择师训项目')
        return
      }
      this.signOverviewDialogVisible = true
      this.$nextTick(() => {
        this.$refs.signOverviewDialog.init(this.query.trainId)
      })
    },
    handleAuditLog() {
      this.auditLogDialogVisible = true
      this.$nextTick(() => {
        this.$refs.auditLogDialog.init()
      })
    },
    handleExport() {
      this.$confirm('是否确认导出所有签到记录数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _query = {
          ...this.listQuery,
          ...this.query
        }
        exportSignRecords(_query).then(response => {
          const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = `师训签到记录_${this.$moment().format('YYYY-MM-DD')}.xlsx`
          link.click()
          window.URL.revokeObjectURL(url)
          this.$message.success('导出成功')
        })
      })
    },
    handleDetail(row) {
      this.detailDialogVisible = true
      this.$nextTick(() => {
        this.$refs.detailDialog.init(row)
      })
    },
    handleEditStatus(row) {
      this.editStatusFormVisible = true
      this.$nextTick(() => {
        this.$refs.editStatusForm.init(row)
      })
    },
    handleEditRecord(row) {
      this.editRecordFormVisible = true
      this.$nextTick(() => {
        this.$refs.editRecordForm.init(row)
      })
    },
    handleBatchEdit() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请先选择要编辑的记录')
        return
      }
      this.batchEditFormVisible = true
      this.$nextTick(() => {
        this.$refs.batchEditForm.init(this.multipleSelection)
      })
    },

    /** 获取时段标签 */
    getPeriodLabel(period) {
      const periodMap = {
        1: '上午',
        2: '下午',
        3: '晚上',
        AM: '上午',
        PM: '下午',
        EVE: '晚上'
      }
      return periodMap[period] || period
    },
    /** 获取时段标签类型 */
    getPeriodTagType(period) {
      const typeMap = {
        1: 'success',
        2: 'primary',
        3: 'warning',
        AM: 'success',
        PM: 'primary',
        EVE: 'warning'
      }
      return typeMap[period] || ''
    },
    /** 获取状态标签 */
    getStatusLabel(status) {
      const statusMap = {
        1: '正常签到',
        2: '迟到',
        3: '请假',
        4: '早退',
        5: '缺勤',
        Normal: '正常签到',
        Late: '迟到',
        Leave: '请假',
        EarlyLeave: '早退',
        Absent: '缺勤'
      }
      return statusMap[status] || status
    },
    /** 获取状态标签类型 */
    getStatusTagType(status) {
      const typeMap = {
        1: 'success',
        2: 'warning',
        3: 'info',
        4: 'warning',
        5: 'danger',
        Normal: 'success',
        Late: 'warning',
        Leave: 'info',
        EarlyLeave: 'warning',
        Absent: 'danger'
      }
      return typeMap[status] || ''
    },
    /** 获取签到方式标签 */
    getMethodLabel(method) {
      const methodMap = {
        1: '二维码签到',
        2: '手动签到',
        3: '自动生成',
        QR: '二维码签到',
        MANUAL: '手动签到',
        AUTO: '自动生成'
      }
      return methodMap[method] || method
    },
    /** 获取签到方式标签类型 */
    getMethodTagType(method) {
      const typeMap = {
        1: 'primary',
        2: 'warning',
        3: 'info',
        QR: 'primary',
        MANUAL: 'warning',
        AUTO: 'info'
      }
      return typeMap[method] || ''
    },
    /** 获取状态图标 */
    getStatusIcon(status) {
      const iconMap = {
        1: 'el-icon-check',
        2: 'el-icon-warning',
        3: 'el-icon-info',
        4: 'el-icon-warning-outline',
        5: 'el-icon-close',
        Normal: 'el-icon-check',
        Late: 'el-icon-warning',
        Leave: 'el-icon-info',
        EarlyLeave: 'el-icon-warning-outline',
        Absent: 'el-icon-close'
      }
      return iconMap[status] || 'el-icon-question'
    }
  }
}
</script>

<style lang="scss" scoped>
.status-tag {
  &.success {
    color: #67c23a;
  }

  &.warning {
    color: #e6a23c;
  }

  &.danger {
    color: #f56c6c;
  }

  &.info {
    color: #909399;
  }
}

.empty-state {
  padding: 60px 0;
  text-align: center;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

// 状态标签增强样式
.status-tag-enhanced {
  display: inline-flex;
  align-items: center;
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .status-icon {
    margin-right: 4px;
    font-size: 12px;
    display: inline-block;
  }
}

// 快速筛选区域样式
.quick-filter-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  margin: 8px 0;

  .filter-label {
    font-size: 14px;
    color: #606266;
    margin-right: 12px;
    font-weight: 500;
    white-space: nowrap;
  }

  .filter-buttons {
    flex: 1;
    margin: 0 16px;

    .el-button {
      border-radius: 4px;
      margin-right: 8px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      }

      i {
        margin-right: 4px;
      }
    }
  }

  .export-actions {
    display: flex;
    align-items: center;
    white-space: nowrap;

    .el-button {
      margin-left: 8px;

      &:first-child {
        margin-left: 0;
      }
    }
  }
}


</style>
